import { defineStore } from "pinia";
import { loginApi } from "../api/user";

interface LoginParam {
  username: string;
  password: string;
}

export const useUserStore = defineStore("user", {
  state: () => ({
    token: sessionStorage.getItem("token") || "",
    //!代表非空断言
    roles: sessionStorage.getItem("roles")
      ? JSON.parse(sessionStorage.getItem("roles")!)
      : [],

    username: sessionStorage.getItem("username") || "",

    menu: sessionStorage.getItem("menu")
      ? JSON.parse(sessionStorage.getItem("menu")!)
      : [],
  }),

  actions: {
    async login(data: LoginParam) {
      try {
        const {
          data: {
            menulist,
            token,
            user: { username, roles },
          },
        } = await loginApi(data);

        this.token = token;
        this.roles = roles;
        this.username = username;
        this.menu = menulist;
        //pinia不能持久化存储，存储本地
        sessionStorage.setItem("token", token);
        sessionStorage.setItem("roles", JSON.stringify(roles));
        sessionStorage.setItem("username", username);
        sessionStorage.setItem("menu", JSON.stringify(menulist));
      } catch (err) {
        console.log("error", err);
      }
    },

    // 退出登录
    logout() {
      this.token = "";
      this.roles = [];
      this.username = "";
      this.menu = [];
      sessionStorage.clear();
    },
  },
});
